//
// Created by steven on 2017/2/23.
// Copyright (c) 2017 steven. All rights reserved.
//

#import "GMSubUserViewController.h"
#import "GMAccountTableViewCell.h"
#import "GMSubUserDetailViewController.h"
#import "GMSubUserAddViewController.h"
#import "GMSubUserDataController.h"
#import "GMSubUserModel.h"
#import <MJRefresh/MJRefresh.h>
#import <SDWebImage/UIImageView+WebCache.h>

#define kAccountTableViewCellIdentifier @"kAccountTableViewCellIdentifier"

@interface GMSubUserViewController()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong)NSMutableArray *subUserRecords;
@property (nonatomic, strong)GMSubUserDataController *subUserDataController;
@property (nonatomic, strong)UITableView *tableView;

@end

@implementation GMSubUserViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.subUserDataController = [[GMSubUserDataController alloc] init];
    self.subUserRecords = [[NSMutableArray alloc] init];

    [self setupMainView];
    [self setMJRefresh];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"添加子账户"
                                                                           style:UIBarButtonItemStylePlain
                                                                          target:self
                                                                          action:@selector(rightBarButtonItemPressed)];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;

    [self refreshSubUsers];
}

#pragma mark - set up main view
- (void)setupMainView {
    self.navigationItem.title = @"账号管理";

    [self.view addSubview:self.tableView];
    [self.tableView autoPinEdgesToSuperviewEdges];
}

#pragma mark - set MJRefresh
- (void)setMJRefresh {

    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if(weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf refreshSubUsers];
        }
    }];

    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (weakSelf) {
            __strong typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf loadMoreSubUsers];
        }
    }];
    self.tableView.mj_footer.automaticallyHidden = YES;
}

#pragma mark - right barButton pressed
- (void)rightBarButtonItemPressed {
    GMSubUserAddViewController *accountAddViewController = [[GMSubUserAddViewController alloc] init];
    [self.navigationController pushViewController:accountAddViewController animated:YES];
}

#pragma mark - refresh account
- (void)refreshSubUsers {
    NSDictionary *params = @{@"page":@"1", @"perpage":PER_PAGE_RECORD};
    [self requestSubUsersWithParams:params];
}

#pragma mark - load more subusers
- (void)loadMoreSubUsers {
    NSInteger currentPage = self.subUserDataController.subUserRecord.currentPage;
    NSInteger totalPage = self.subUserDataController.subUserRecord.totalPage;
    if (currentPage < totalPage) {
        NSDictionary *faceParams = @{@"page":[NSString stringWithFormat:@"%ld", currentPage+1],@"perpage":PER_PAGE_RECORD};
        [self requestSubUsersWithParams:faceParams];
    } else {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}

#pragma mark - requestTopFacesWithParams
- (void)requestSubUsersWithParams:(NSDictionary *)params {
    [self.subUserDataController requestSubUsersWithParams:params callback:^(NSString *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error == nil) {
                [self renderSuccessView];
            } else {
                [self showAlertMessage:error];
            }
        });
    }];
}

#pragma mark - render success view
- (void)renderSuccessView {
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
    self.subUserRecords = self.subUserDataController.subUserRecord.subUsers;
    [self.tableView reloadData];
}

#pragma mark - account table view
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = BACKGROUND_COLOR;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[GMAccountTableViewCell class] forCellReuseIdentifier:kAccountTableViewCellIdentifier];
    }

    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.subUserRecords.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GMAccountTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kAccountTableViewCellIdentifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[GMAccountTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kAccountTableViewCellIdentifier];
    }

    GMSubUserModel *subUserModel = self.subUserRecords[indexPath.row];

    [cell.avatarImageView sd_setImageWithURL:[[NSURL alloc] initWithString:subUserModel.headImg] placeholderImage:[UIImage imageNamed:@"default-user-icon"]];
    cell.nameLabel.text = subUserModel.name;
    cell.phoneLabel.text = subUserModel.account;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 88;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    GMSubUserModel *subUserModel = self.subUserRecords[indexPath.row];

    GMSubUserDetailViewController *subUserDetailViewController = [[GMSubUserDetailViewController alloc] init];
    subUserDetailViewController.subUserModel = subUserModel;
    [self.navigationController pushViewController:subUserDetailViewController animated:YES];
}

#pragma mark - remove cell
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        GMSubUserModel *subUserModel = self.subUserRecords[indexPath.row];
        NSDictionary *params = @{@"id": [NSString stringWithFormat:@"%ld", subUserModel.id]};
        [self.subUserDataController deleteSubUserWithParams:params callback:^(NSString *error) {
            if (error == nil) {
                [self refreshSubUsers];
            } else {
                [self showAlertMessage:error];
            }
        }];
    }
}

@end
